from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from .models import Area
from .serializers import AreaSerializer, SubsAreaSerializer
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin, RetrieveCacheResponseMixin, \
    CacheResponseMixin

# Create your views here.


class AreaView(CacheResponseMixin, ReadOnlyModelViewSet):
    """
    省份信息  select * from tb_areas where parent_id is Null;
    
    市信息    select * from tb_areas where parent_id=320000;
    区县信息  select * from tb_areas where parent_id=321000;
    
    省份信息的url   areas/infos/        list
    市区县的url     areas/infos/pk/     retrieve
    """""
    pagination_class = None
    # 设置数据查询结果集
    # 重写这个方法,根据不同的业务逻辑返回不同的查询数据
    def get_queryset(self):

        if self.action == 'list':
            # 省份信息
            return Area.objects.filter(parent__isnull=True)
        else:
            # 区县信息
            # 会根据url中传递的pk来获取指定的数据
            return Area.objects.all()

    def get_serializer_class(self):

        if self.action == 'list':
            return AreaSerializer
        else:
            return SubsAreaSerializer
